package com.tg.app.activity.device;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.wifi.WifiConfiguration;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.util.Consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.appbase.custom.base.DeviceFeatureSettings;
import com.appbase.custom.base.ServiceBought;
import com.appbase.custom.constant.CommonConstants;
import com.appbase.custom.constant.DeviceStateConstants;
import com.base.BaseActivity;
import com.demo.view.SettingItemTextView;
import com.tange.base.toolkit.NetworkUtil;
import com.tange.base.toolkit.PreferenceUtil;
import com.tange.base.toolkit.StringUtils;
import com.tange.core.backend.service.http.ClientObserver;
import com.tange.core.device.facade.ConnectStatus;
import com.tange.core.device.facade.DeviceFacade;
import com.tange.core.device.facade.Instruction;
import com.tange.core.device.facade.Status;
import com.tange.core.device.manage.DeviceUnbind;
import com.tange.core.sharing.DeviceSharing;
import com.tange.module.camera.hub.CameraHub;
import com.tange.module.core.wifi.scan.ApScanConfiguration;
import com.tange.module.core.wifi.scan.WiFiScanManager;
import com.tange.module.core.wifi.scan.WifiCipherType;
import com.tange.module.device.feature.DeviceFeature;
import com.tange.module.device.feature.DeviceFeatureObjectBox;
import com.tange.module.device.feature.DeviceInteraction;
import com.tange.module.socket.SocketIoConstants;
import com.tg.app.R;
import com.tg.app.activity.ChangeDeviceNameActivity;
import com.tg.app.activity.base.DeviceListBaseActivity;
import com.tg.app.activity.device.settings.DeviceInfoActivity;
import com.tg.app.activity.device.settings.SpeakerVolumeActivity;
import com.tg.app.camera.AVIOCTRLDEFs;
import com.tg.app.helper.ActivityHelper;
import com.tg.app.helper.AppHelper;
import com.tg.app.helper.DeviceFeatureHelper;
import com.tg.app.helper.DeviceHelper;
import com.tg.app.helper.ServiceInfoHelper;
import com.tg.app.util.LocalThumbnailUtils;
import com.tg.app.util.LogUtils;
import com.tg.app.util.ObjectBoxUtil;
import com.tg.appcommon.android.LanguageUtils;
import com.tg.appcommon.android.Packet;
import com.tg.appcommon.android.TGAlertDialog;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGToast;
import com.tg.data.bean.DeviceItem;
import com.tg.data.bean.DeviceSettingsInfo;
import com.tg.data.bean.DeviceSettingsInfo_;
import com.tg.data.http.entity.DeviceServiceStatusBean;
import com.tg.data.http.entity.GuardDisplayBean;
import com.tg.network.socket.http.TGHttp;

import java.io.Serializable;
import java.util.HashMap;

import io.objectbox.Box;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

@SuppressLint("UseSwitchCompatOrMaterialCode")
public class DeviceSettingsActivity extends BaseActivity implements View.OnClickListener, Serializable {
    public static final String TAG = DeviceSettingsActivity.class.getSimpleName();
    public static final int DEVICE_INFO_ACTIVITY = 0;
    public static final int RECORD_MODE_ACTIVITY = 1;
    public static final int CLOUD_RESOLUTION_ACTIVITY = 2;
    public static final int RECORD_CHECK_ACTIVITY = 3;
    public static final int SDCARD_STATE_ACTIVITY = 4;
    public static final int ROTATE_ACTIVITY = 5;
    public static final int DEVICE_SHARE_LIST_ACTIVITY = 6;
    public static final int CLOUD_SERVICE_ACTIVITY = 7;
    public static final int TIME_ZONE_ACTIVITY = 9;
    public static final int NIGHT_VISION_ACTIVITY = 10;
    public static final int LIGHT_SETTINGS_ACTIVITY = 11;
    public static final int AI_SERVICE_ACTIVITY = 12;
    public static final int CHANGE_DEVICE_WIFI_ACTIVITY = 13;
    public static final int ADD_CHOOSE_ACTIVITY = 14;
    public static final int NOTIFICAION_INTERVAL_ACTIVITY = 15;
    public static final int SIM_SERVICE_ACTIVITY = 18;
    public static final int DEVICE_SLEEP_ACTIVITY = 19;
    public static final int ALERT_SOUND_ACTIVITY = 21;
    public static final int CAR_SERVICE_ACTIVITY = 23;
    public static final int VIDEO_SETTINGS_ACTIVITY = 25;
    public static final int BATTERY_SLEEP_ACTIVITY = 26;
    public static final int SPEAKER_VOLUME_ACTIVITY = 27;
    public static final int PIR_ACTIVITY = 28;
    public static final int REBOOT_ACTIVITY = 29;
    public static final int MORE_SETTING = 30;
    public static final int NETWORK_SETTING = 31;
    public static final int SMART_SPEAKERS_SETTING = 308;
    public static final int CUSTOMER_DEVICE_SETTING = 311;
    public static final int AUTO_TRACKING_ACTIVITY = 20;
    public static final int TUMVLE_SETTING = 317;


    private DeviceFacade deviceFacade;
    private DeviceItem mDevice;
    private Intent cruiseData = null;
    public static final String EXT_DEVICE_INFO = "settings_ext_device_info";
    public static final String ACTION_DEVICE_SETTINGS = "Intent_action_device_settings";

    @SuppressLint("UseSwitchCompatOrMaterialCode")

    Boolean mIsReadSuccess = false;
    private DeviceSettingHelper.DeviceSettingsBroadcastReceiver receiver;
    private RelativeLayout mShareRl, mSDCardStateRl, mPictureRl, mRebootBtn;

    private SettingItemTextView mDoubleLightRl, mAutoTraceRl, mBuzzerRL;

    private LinearLayout advancedLayout;
    private Button mDeleteDeviceBtn;
    private TextView deviceName;
    Handler handler = new Handler();
    private int origin = 0;
    public DeviceSettingsInfo mDeviceSettingsInfo;
    private DeviceFeature deviceFeature;
    private boolean hasLoadData = false;

    public int eCharEncoding = -1;


    public DeviceSettingsActivity() {
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.activity_settings);
        hideActionBar();
        getIntentData();
        initView();
        connectAndCmd();
        registerReceiver();
    }

    @Override
    public boolean shouldSetStatusBarColor() {
        return true;
    }


    private void showWaterMarkSetting() {
        boolean show = showWatermark() || DeviceFeatureHelper.supportMultiChannels(deviceFeature);
        mPictureRl.setVisibility(show ? View.VISIBLE : View.GONE);
    }

    private void connectAndCmd() {
        // TODO：此处逻辑优化为被动设备都不主动连接，而不只是门锁
        if (!DeviceHelper.isPassiveLockBell(mDevice)){
            if (deviceFacade != null && NetworkUtil.isNetworkConnected(TGApplicationBase.getApplication())) {
                if (!isShareDevice() && !DeviceHelper.is4GExpired(mDevice)) {
                    if (!deviceFacade.connected()) {
                        startrreadui();
                        deviceFacade.connect();
                    }
                }
                if (deviceFacade.connected()) {
                    startrreadui();
                    sendCmd();
                }
            }
        }
    }

    private void getIntentData() {
        Intent intent = getIntent();
        mDevice = intent.getParcelableExtra(CommonConstants.EXT_DEVICE_ITEM);
        origin = intent.getIntExtra(CommonConstants.EXT_PUSH_ORIGIN, 0);
        if (mDevice != null) {
            deviceFeature = DeviceFeatureObjectBox.queryDeviceFeature(mDevice.uuid);
            parseServerDeviceFeature();
            deviceFacade = new DeviceFacade(mDevice.uuid);
        }

        Box<DeviceSettingsInfo> deviceSettingsInfoBox = ObjectBoxUtil.getDeviceSettingsInfo();
        if (mDevice != null) {
            assert deviceSettingsInfoBox != null;
            mDeviceSettingsInfo = deviceSettingsInfoBox.query().equal(DeviceSettingsInfo_.uuid, mDevice.uuid).build().findFirst();
            if (mDeviceSettingsInfo == null) {
                mDeviceSettingsInfo = new DeviceSettingsInfo();
                updateInfo();
            }
            mDeviceSettingsInfo.deviceStatus = mDevice.is_open;
        }

        registerICameraListener();
    }

    private void registerICameraListener(){
        if (deviceFacade != null) {
            deviceFacade.observeConnectStatus(connectStatusConsumer);
            deviceFacade.getInstruct().observeOnReceive(instructionConsumer);
        }
    }

    private void unregisterICameraListener(){
        if (deviceFacade != null) {
            deviceFacade.unObserveConnectStatus(connectStatusConsumer);
            deviceFacade.getInstruct().unObserveOnReceive(instructionConsumer);
        }
    }

    private void parseServerDeviceFeature() {
        if (deviceFeature != null) {
            TGLog.i(TAG, "[parseServerDeviceFeature] skip.");
            return;
        }
        deviceFeature = DeviceFeatureHelper.getDeviceFeatureByDevice(mDevice);
    }

    private void registerReceiver() {
        receiver = DeviceSettingHelper.registerReceiver(this, (context, intent) -> {
            if (ACTION_DEVICE_SETTINGS.equals(intent.getAction())) {
                DeviceSettingsInfo rInfo = intent.getParcelableExtra(EXT_DEVICE_INFO);
                if (rInfo != null) {
                    rInfo.id = mDeviceSettingsInfo.id;
                    mDeviceSettingsInfo = rInfo;
                    updateSettings();
                }

                DeviceItem deviceItem = intent.getParcelableExtra(CommonConstants.EXT_DEVICE_ITEM);
                if (deviceItem != null){
                    mDevice = deviceItem;
                    mDeviceSettingsInfo.deviceStatus = mDevice.is_open;
                }
            }
        });
    }

    private boolean isShareDevice(){
        return mDevice.isShare();
    }


    public void initView() {
        deviceName = findViewById(R.id.tv_device_name);
        deviceName.setText(mDevice.name);
        mDeleteDeviceBtn = findViewById(R.id.btn_settings_delete_device);
        mRebootBtn = findViewById(R.id.btn_settings_device_reboot);
        mBuzzerRL = findViewById(R.id.rl_settings_buzzer);
        mShareRl = findViewById(R.id.rl_settings_share);
        mSDCardStateRl = findViewById(R.id.rl_settings_sdcard_state);
        mDoubleLightRl = findViewById(R.id.rl_settings_double_light);
        mAutoTraceRl = findViewById(R.id.rl_settings_auto_tracking);

        advancedLayout = findViewById(R.id.settings_advanced);


        mPictureRl = findViewById(R.id.rl_settings_picture);

        setViewListener();
        setViewVisibility();
        setDeviceState();
        setBuzzerName();
    }


    private void setBuzzerName(){
        mBuzzerRL.setName(R.string.txt_warning_voice);
    }

    private void setDeviceState() {
        if (mDevice == null) {
            return;
        }

        if (mSDCardStateRl != null){
            mSDCardStateRl.setVisibility(DeviceHelper.isPassiveDoorBellDevice(mDevice) || DeviceFeatureHelper.isNoMedia(deviceFeature) || isShareDevice() ? View.GONE : View.VISIBLE);
        }
    }

    private void doJumpInfo(){
        DeviceSettingHelper.doJump(DeviceSettingsActivity.this, DeviceSettingsActivity.DEVICE_INFO_ACTIVITY, mDeviceSettingsInfo, mDevice);
    }

    private void setViewListener() {
        findViewById(R.id.ib_settings_back_toolbar).setOnClickListener(this);
        findViewById(R.id.ll_settings_base).setOnClickListener(v -> {
            Intent intent = new Intent(DeviceSettingsActivity.this, ChangeDeviceNameActivity.class);
            intent.putExtra(DeviceInfoActivity.EXT_DEVICE_NAME, mDevice.name);
            intent.putExtra(CommonConstants.EXT_DEVICE_ID, mDevice.uuid);
            startActivityForResult(intent, 0);
        });

        findViewById(R.id.rl_device_detail).setOnClickListener(v -> doJumpInfo());
        mDeleteDeviceBtn.setOnClickListener(this);
        mRebootBtn.setOnClickListener(this);
        mAutoTraceRl.setOnClickListener(this);
        mShareRl.setOnClickListener(this);
        mSDCardStateRl.setOnClickListener(this);
        mDoubleLightRl.setOnClickListener(this);
        mPictureRl.setOnClickListener(this);
        mBuzzerRL.setOnClickListener(this);
    }

    private void setViewVisibility() {
        mShareRl.setVisibility(mDevice.isShare()? View.GONE : View.VISIBLE);
        findViewById(R.id.iv_device_name_edit).setVisibility(isShareDevice()? View.GONE : View.VISIBLE);
        findViewById(R.id.settings_advanced).setVisibility(isShareDevice()? View.GONE : View.VISIBLE);
        findViewById(R.id.tv_settings_advanced).setVisibility(isShareDevice()? View.GONE : View.VISIBLE);
        findViewById(R.id.rl_settings_share_user_tip).setVisibility(isShareDevice()? View.VISIBLE: View.GONE);
        mAutoTraceRl.setVisibility(View.GONE);
        if (isShareDevice()) {
            advancedLayout.setVisibility(View.GONE);
            mSDCardStateRl.setVisibility(View.GONE);
            mShareRl.setVisibility(View.GONE);

            mRebootBtn.setVisibility(View.GONE);

            mDeleteDeviceBtn.setText(R.string.settings_exit_share);
            mDeleteDeviceBtn.setAllCaps(false);
        } else {
            getFeatureCmd();
        }


        mSDCardStateRl.setVisibility(DeviceHelper.isPassiveDoorBellDevice(mDevice) || DeviceFeatureHelper.isNoMedia(deviceFeature) || isShareDevice() ? View.GONE : View.VISIBLE);


    }

    private boolean showWatermark(){
        if (eCharEncoding  == -1){
            return false;
        }
        if (eCharEncoding == StringUtils.CHAR_ENCODING_UTF8){
            return true;
        }
        if (eCharEncoding ==  StringUtils.CHAR_ENCODING_GB2312 || eCharEncoding ==  StringUtils.CHAR_ENCODING_GBK){
            String language = LanguageUtils.getLanguage(getBaseContext());
            TGLog.d("language ===== " + language);
            if (StringUtils.isEmpty(language)){
                return false;
            }
            return language.equalsIgnoreCase(LanguageUtils.ZH_CN) || language.startsWith(LanguageUtils.LANGUAGE_EN);
        }

        if (eCharEncoding ==  StringUtils.CHAR_ENCODING_US_ASCII) {
            String language = LanguageUtils.getLanguage(getBaseContext());
            if (StringUtils.isEmpty(language)){
                return false;
            }
            return language.startsWith(LanguageUtils.LANGUAGE_EN);
        }

        return false;
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        TGLog.i(TAG, "onNewIntent");
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (deviceFacade != null) {
            deviceFeature = DeviceFeatureObjectBox.queryDeviceFeature(mDevice.uuid);
            parseServerDeviceFeature();

            if (!isShareDevice()) {
                if (mDevice.is_online == CommonConstants.DEVICE_ONLINE) {
                    if (deviceFeature == null && !hasLoadData) {
                        if (NetworkUtil.isNetworkConnected(TGApplicationBase.getApplication())) {
                            showLoading();
                            startrreadui();
                            hasLoadData = true;
                        }
                    }
                    getFeatureCmd();
                } else {
                    showToast(R.string.live_offline);
                }

                registerICameraListener();
            }
        }

        updateInfo();
        if (origin == DeviceListBaseActivity.OPEN_DRIVE_LOCAL) {
            mDeleteDeviceBtn.setVisibility(View.GONE);
        }

        TGLog.d(TAG, "onResume == mDeviceSettingsInfo.deviceStatus = ");

        setDeviceState();

        deviceDetail();
    }


    private void updateInfo(){
        if (mDevice != null && mDeviceSettingsInfo != null) {
            mDeviceSettingsInfo.deviceID = mDevice.id;
            mDeviceSettingsInfo.uuid = mDevice.uuid;
            mDeviceSettingsInfo.online = (mDevice.is_online == DeviceStateConstants.DEVICE_ONLINE);
            mDeviceSettingsInfo.firmware_id = mDevice.firmware_id;
            mDeviceSettingsInfo.timezone = mDevice.timezone;

        }
    }


    @Override
    protected void onPause() {
        super.onPause();

        unregisterICameraListener();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
        handler.removeCallbacksAndMessages(null);
    }

    public void deviceDetail() {
        String uuid  =  mDevice == null? "0" : mDevice.uuid;

        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("uuid", uuid);
        TGHttp.getInstance().getAiGuardDisplay(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ClientObserver<GuardDisplayBean>() {
                    @Override
                    protected void onSuccess(GuardDisplayBean content) {
                        TGLog.d("content = " + content);


                    }
                });
    }

    @Override
    public void onBackPressed() {
        goBack();
    }

    private void goBack() {
        Intent resultIntent = new Intent();
        resultIntent.putExtra(CommonConstants.EXT_DEVICE_ITEM, mDevice);
        if (mDevice != null) {
            TGLog.d(TAG, "ispen" + mDevice.is_open);
        }

        if (cruiseData != null && DeviceFeatureHelper.isSupportCruise(deviceFeature) && deviceFacade != null && !isShareDevice()){
            cruiseData.putExtra(CommonConstants.EXT_DEVICE_ITEM, mDevice);
        }else{
            //设置返回数据
            setResult(RESULT_OK, resultIntent);//设置给之前启动它的activity的一个返回码
        }

        this.finish();
    }

    private String getItemTitle(View v) {
        if (v instanceof SettingItemTextView) {
            return ((SettingItemTextView) v).getName();
        }
        return "";
    }

    @Override
    public void onClick(View v) {
        String btnActionName = "";
        String title = getItemTitle(v);

        int id = v.getId();
        if (id == R.id.btn_settings_delete_device) {
            btnActionName = "device_delete";
            deleteDeviceEvent();
        } else if (id == R.id.rl_settings_buzzer) {
            doJump(ALERT_SOUND_ACTIVITY, title);
            btnActionName = "buzzer";
        } else if (id == R.id.rl_settings_auto_tracking) {
            doJump(AUTO_TRACKING_ACTIVITY, title);
            btnActionName = "auto_tracking";
        } else if (id == R.id.btn_settings_device_reboot) {
            doJump(REBOOT_ACTIVITY, title);
            btnActionName = "device_reboot";
        } else if (id == R.id.ib_settings_back_toolbar) {
            goBack();
        } else if (id == R.id.rl_settings_sdcard_state) {
            doJump(SDCARD_STATE_ACTIVITY, title);
            btnActionName = "sdcard_state";
        } else if (id == R.id.rl_settings_rotate) {
            doJump(ROTATE_ACTIVITY, title);
            btnActionName = "rotate";
        } else if (id == R.id.rl_settings_share) {
            doJump(DEVICE_SHARE_LIST_ACTIVITY, title);
            btnActionName = "share";
        }  else if (id == R.id.rl_settings_double_light) {
            if (deviceFeature != null) {
//                if (deviceFeature.dayNightAuto) {
//                    doJump(DAY_NIGHT_AUTO_ACTIVITY, title);
//                    btnActionName = "day_light_auto";
//                } else if (deviceFeature.isDayNightOnly()) {
//                    doJump(NIGHT_VISION_ACTIVITY, title);
//                    btnActionName = "night_vision";
//                } else if (deviceFeature.isDoubleLightOnly()) {
//                    doJump(DOUBLE_LIGHT_ACTIVITY, title);
//                    btnActionName = "double_light";
//                } else {
//
//                }
                doJump(LIGHT_SETTINGS_ACTIVITY, title);
                btnActionName = "light_settings";
            }
        }   else if (id == R.id.rl_settings_picture) {
            doJump(ROTATE_ACTIVITY, title);
            btnActionName = "picture";
        }
        if (!TextUtils.isEmpty(btnActionName)) {
            LogUtils.onEventClickByName("device_settings", btnActionName);
        }

    }



    private void deleteDeviceEvent() {

        if (isShareDevice()){
            new TGAlertDialog(this).builder().setTitle(R.string.settings_exit_share_confirm).setPositiveButton(R.string.confirm, v -> {
                if (!NetworkUtil.isNetworkConnected(TGApplicationBase.getApplication())) {
                    TGToast.showToast(R.string.txt_network_anomaly);
                    return;
                }
                quitDeviceShare();
            }).setNegativeButton(getString(R.string.cancel), v -> {
            }).show();
        }else{
            new TGAlertDialog(this).builder(R.layout.dialog_custom_style4).setTitle(R.string.delete_device).setMessage(R.string.dialog_delete_device_desc).setPositiveButton(R.string.delete_device_confirm, v -> {
                if (!NetworkUtil.isNetworkConnected(TGApplicationBase.getApplication())) {
                    TGToast.showToast(R.string.txt_network_anomaly);
                    return;
                }
                deleteFromServer();
            }).setNegativeButton(getString(R.string.cancel), v -> {
            }).show();
        }


    }

    private void doJump(int whichActivity, String title) {
        DeviceSettingHelper.doJump(DeviceSettingsActivity.this, whichActivity, mDeviceSettingsInfo, mDevice, title);
    }

    private void removeZoom() {
        String near = String.format("%s_%s", CommonConstants.PRE_LENSES_CAP_ZOOM_NEAR, mDevice.uuid);
        PreferenceUtil.remove(getBaseContext(), near);
        String far = String.format("%s_%s", CommonConstants.PRE_LENSES_CAP_ZOOM_FAR, mDevice.uuid);
        PreferenceUtil.remove(getBaseContext(), far);
    }

    private void quitDeviceShare() {
        DeviceSharing.INSTANCE.quit(mDevice.uuid, ret -> {
            if (ret.getSuccess()) {
                LocalThumbnailUtils.getInstance().deleteBitmap(mDevice.uuid);
                CameraHub.getInstance().setEnableLocalApConnect(false);
                showToast(R.string.delete_success);
                PreferenceUtil.setString(getBaseContext(), mDevice.uuid, "");
                removeZoom();
                CameraHub.getInstance().removeCamera(mDevice.uuid);
                int num = PreferenceUtil.getInt(DeviceSettingsActivity.this, CommonConstants.PRE_DEVICE_NUM, 0);
                PreferenceUtil.setInt(DeviceSettingsActivity.this, CommonConstants.PRE_DEVICE_NUM, num - 1);
                ActivityHelper.gotoDeviceListPage(DeviceSettingsActivity.this);
                removeDeviceFeature();
                removeDeviceSetting();
                finish();
            }else{
                showToast(R.string.share_failed);
            }
        });
    }

    private void deleteFromServer() {
        showLoading();
        DeviceUnbind.INSTANCE.require(deviceFacade.getDeviceId(), ret -> {
            if (ret.getSuccess()){
                LocalThumbnailUtils.getInstance().deleteBitmap(mDevice.uuid);
                CameraHub.getInstance().setEnableLocalApConnect(false);
                showToast(R.string.delete_success);
                PreferenceUtil.setString(getBaseContext(), mDevice.uuid, "");
                removeZoom();
                CameraHub.getInstance().removeCamera(mDevice.uuid);
                int num = PreferenceUtil.getInt(DeviceSettingsActivity.this, CommonConstants.PRE_DEVICE_NUM, 0);
                PreferenceUtil.setInt(DeviceSettingsActivity.this, CommonConstants.PRE_DEVICE_NUM, num - 1);
                ActivityHelper.gotoDeviceListPage(DeviceSettingsActivity.this);
                removeDeviceFeature();
                removeDeviceSetting();
                finish();
            }else{
                TGToast.showToast(ret.getMessage());
            }
            hideLoading();
        });
    }

    private void removeDeviceFeature() {
        if (deviceFacade != null) {
            Box<DeviceFeature> featureBox = DeviceFeatureObjectBox.getDeviceFeature();
            DeviceFeature feature = DeviceFeatureObjectBox.queryDeviceFeature(mDevice.uuid);
            if (featureBox != null && feature != null) {
                featureBox.remove(feature);
            }
        }
    }

    private void removeDeviceSetting() {
        if (deviceFacade != null) {
            Box<DeviceSettingsInfo> box  = ObjectBoxUtil.getDeviceSettingsInfo();
            if (mDeviceSettingsInfo != null&&mDeviceSettingsInfo.id!=0) {
                box.remove(mDeviceSettingsInfo);
            }
        }
    }

    private void setBuzzerVisibility() {
        if (deviceFeature.supportBuzzer) {
            mBuzzerRL.setVisibility(View.VISIBLE);
        }else{
            mBuzzerRL.setVisibility(View.GONE);
        }
    }

    public void getFeatureCmd() {

        if (deviceFeature != null && !isShareDevice()) {
            if (deviceFeature.autoTracking) {
                mAutoTraceRl.setVisibility(View.VISIBLE);
            }
//            if (deviceFeature.dayNight || deviceFeature.dayNightAuto || deviceFeature.doubleLight) {
//                mDoubleLightRl.setVisibility(View.VISIBLE);
//                if (deviceFeature.dayNightAuto) {
//                    mDoubleLightRl.setName(R.string.settings_double_light);
//                } else if (deviceFeature.isDayNightOnly()) {
//                    mDoubleLightRl.setName(R.string.settings_night_mode);
//                } else if (deviceFeature.isDoubleLightOnly()) {
//                    mDoubleLightRl.setName(R.string.settings_double_light);
//                }
//            }
            setBuzzerVisibility();

            if (deviceFacade == null){
                return;
            }

            if (!NetworkUtil.isNetworkConnected(TGApplicationBase.getApplication())) {
                return;
            }
            if (deviceFeature.supportCloseDevice && !CameraHub.getInstance().isEnableLocalApConnect()) {
                AppHelper.sendIOCtrl(deviceFacade, AVIOCTRLDEFs.TCL_CMD_GET_CAMERA_STATUS_REQ, new byte[1]);
            }


            if (deviceFeature.supportDeviceBroadcast) {
                AppHelper.sendIOCtrl(deviceFacade, AVIOCTRLDEFs.TCI_CMD_GET_VOICE_PROMPT_STATUS_REQ, new byte[1]);
            }

            if (deviceFeature.isSupportSettingCarParkingMonitor) {
                if (mDevice != null && mDevice.getCarServerData() != null) {
                    TGLog.d("CarEmergencySensitivity", "send GSENSOR_SCENE_DRIVING");
                    TGLog.d("CarEmergencySensitivity", "send GSENSOR_SCENE_PARKING");
                }
            }

            if (deviceFeature.supportStatusLed) {
                AppHelper.sendIOCtrl(deviceFacade, AVIOCTRLDEFs.TCI_CMD_GET_LED_STATUS_REQ, new byte[1]);
            }
            if (deviceFeature.supportAlarmLight) {
                AppHelper.sendIOCtrl(deviceFacade, AVIOCTRLDEFs.TCI_CMD_GET_ALARMLIGHT_REQ, new byte[1]);
            }
            if (deviceFeature.supportAiSwitch) {
                AppHelper.sendIOCtrl(deviceFacade, AVIOCTRLDEFs.TCI_CMD_GET_AI_REQ, new byte[1]);
            }
        }
    }


    private void sendCmd() {
        if (deviceFacade != null) {
            //设备信息：SD卡容量，ID号，版本号等
            AppHelper.sendIOCtrl(deviceFacade, AVIOCTRLDEFs.IOTYPE_USER_IPCAM_DEVINFO_REQ, AVIOCTRLDEFs.SMsgAVIoctrlDeviceInfoReq.parseContent());
            if (!isShareDevice()) {
                //视频180度旋转
                AppHelper.sendIOCtrl(deviceFacade, AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GET_VIDEOMODE_REQ, AVIOCTRLDEFs.SMsgAVIoctrlGetVideoModeReq.parseContent(0));
                //高清视频类型
                AppHelper.sendIOCtrl(deviceFacade, AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETSTREAMCTRL_REQ, AVIOCTRLDEFs.SMsgAVIoctrlGetStreamCtrlReq.parseContent(0));

                //防闪烁
                AppHelper.sendIOCtrl(deviceFacade, AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GET_ENVIRONMENT_REQ, AVIOCTRLDEFs.SMsgAVIoctrlGetEnvironmentReq.parseContent(0));
                AppHelper.sendIOCtrl(deviceFacade, AVIOCTRLDEFs.IOTYPE_USEREX_IPCAM_GET_CLOUD_VIDEO_QUALITY_REQ, AVIOCTRLDEFs.SMsgAVIoctrlGetEnvironmentReq.parseContent(0));
                runOnUiThread(this::getFeatureCmd);

                AppHelper.sendIOCtrl(deviceFacade, AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETRECORD_REQ, AVIOCTRLDEFs.SMsgAVIoctrlGetRecordReq.parseContent(0));
                AppHelper.sendIOCtrl(deviceFacade, AVIOCTRLDEFs.TCI_CMD_GET_MAX_AWAKE_TIME_REQ, AVIOCTRLDEFs.SMsgAVIoctrlGetRecordReq.parseContent(0));


            }

        }
    }


    private final Consumer<Instruction> instructionConsumer = new Consumer<Instruction>() {
        @Override
        public void accept(Instruction instruction) {
            if (instruction == null) {
                return;
            }
            final int type = instruction.getId();
            final byte[] data = instruction.getData();
            runOnUiThread(() -> {
                if (type == AVIOCTRLDEFs.IOTYPE_USEREX_IPCAM_DEV_REBOOT_RESP) {
                    mIsReadSuccess = true;
                    handler.removeCallbacks(timeRunnable);
                    long wait = 1000;
                    if (origin == DeviceListBaseActivity.OPEN_DRIVE_LOCAL) {
                        WifiConfiguration exsits = WiFiScanManager.scanner().createWifiConfig(ApScanConfiguration.INSTANCE.apNamePrefix(), null, WifiCipherType.WIFICIPHER_NOPASS);
                        WiFiScanManager.scanner().addNetWork(exsits, getBaseContext());
                        wait = 5 * 1000;
                    }
                    handler.postDelayed(() -> {
                        hideLoading();
                        rebootCompeted();
                    }, wait);
                    return;
                }
                completeread();
                if (type == AVIOCTRLDEFs.TCI_CMD_GET_OSD_RESP) {
                    if (data != null && data.length >= 8){
                        eCharEncoding = Packet.byteArrayToShort_Little(data, 4);
                        showWaterMarkSetting();
                    }
                }else if (type == AVIOCTRLDEFs.IOTYPE_USER_IPCAM_DEVINFO_RESP) {
                    int mTotalSize = Packet.byteArrayToInt_Little(data, 40);
                    int free = Packet.byteArrayToInt_Little(data, 44);
                    mDeviceSettingsInfo.total = mTotalSize;
                    mDeviceSettingsInfo.free = free;
                    byte[] modArr = new byte[16];
                    System.arraycopy(data, 0, modArr, 0, modArr.length);
                    mDeviceSettingsInfo.mode = StringUtils.toString(modArr);
                } else if (type == AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GET_VIDEOMODE_RESP) {
                    mDeviceSettingsInfo.videoMode = data[4];
                } else if (type == AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GET_ENVIRONMENT_RESP) {
                    mDeviceSettingsInfo.envMode = data[4];
                } else if (type == AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETSTREAMCTRL_RESP) {
                    mDeviceSettingsInfo.quality = data[4];
                } else if (type == AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETRECORD_RESP) {
                    mDeviceSettingsInfo.recordType = Packet.byteArrayToInt_Little(data, 4);
                    if (data.length > 8) {
                        mDeviceSettingsInfo.recordStream = data[8];
                    }
                    TGLog.d("VideoType", "recordType3 = " + mDeviceSettingsInfo.recordType);
                    TGLog.d(TGLog.TAG, "recordType" + mDeviceSettingsInfo.recordType + ", recordStream = " + mDeviceSettingsInfo.recordStream);

                } else if (type == AVIOCTRLDEFs.TCI_CMD_GET_MAX_AWAKE_TIME_RESP) {
                    mDeviceSettingsInfo.max_awake_time = Packet.byteArrayToInt_Little(data, 0);
                    TGLog.d(TGLog.TAG, "mDeviceSettingsInfo.max_awake_time = " + mDeviceSettingsInfo.max_awake_time);
                } else if (type == AVIOCTRLDEFs.IOTYPE_USEREX_IPCAM_GET_DOUBLELIGHT_RESP) {
                    mDeviceSettingsInfo.doubleLightMode = Packet.byteArrayToInt_Little(data, 4);
                    mDeviceSettingsInfo.doubleLight = Packet.byteArrayToInt_Little(new byte[]{data[8]});
                } else if (type == AVIOCTRLDEFs.IOTYPE_USEREX_IPCAM_GET_DAYNIGHT_RESP) {
                    mDeviceSettingsInfo.nightVision = Packet.byteArrayToInt_Little(new byte[]{data[8]});
                } else if (type == AVIOCTRLDEFs.IOTYPE_USEREX_IPCAM_GET_MOTION_TRACKER_RESP) {
                    mDeviceSettingsInfo.autoTracking = Packet.byteArrayToInt_Little(new byte[]{data[8]});
                }  else if (type == AVIOCTRLDEFs.IOTYPE_USEREX_IPCAM_GET_FEATURE_RESP) {
                    DeviceFeatureSettings.DeviceFeatureSettingsResp resp = null;
                    try {
                        resp = JSON.parseObject(data, DeviceFeatureSettings.DeviceFeatureSettingsResp.class);
                        TGLog.i(TAG, "DeviceFeatureSettingsResp " + JSON.toJSONString(resp));
                    } catch (Throwable ex) {
                        TGLog.e(TAG, "DeviceFeatureSettingsResp json parse error: " + ex.toString());
                    }

                    if (resp == null) {
                        TGLog.i(TAG, "DeviceFeatureSettingsResp resp == null, maybe json parse error.");
                        return;
                    }

                    DeviceFeature feature = DeviceFeature.newDeviceFeature(resp);
                    if (feature != null) {
                        feature.uuid = mDevice.uuid;
                        if (deviceFeature != null) {
                            feature.id = deviceFeature.id;
                        }
                        deviceFeature = feature;
                    }

                    DeviceSettingsInfo info = DeviceSettingsInfo.newDeviceSettingsInfo(resp);
                    if (info != null) {
                        mDeviceSettingsInfo = DeviceSettingsInfo.updateData(mDeviceSettingsInfo, info, mDevice);
                    }
                    if (mDeviceSettingsInfo != null && deviceFeature != null) {
                        mDeviceSettingsInfo.supportTemper = deviceFeature.supportTemper;
                        mDeviceSettingsInfo.supportHumidity = deviceFeature.supportHumidity;
                    }
                    if (!isShareDevice()) {
                        getFeatureCmd();
                    }
                } else if (type == AVIOCTRLDEFs.TCI_CMD_GET_VOICE_PROMPT_STATUS_RESP) {
                    int status = Packet.byteArrayToInt_Little(data, 0);
                    mDeviceSettingsInfo.deviceBroadcast = status;
                } else if (type == AVIOCTRLDEFs.IOTYPE_USEREX_IPCAM_GET_CLOUD_VIDEO_QUALITY_RESP) {
                    mDeviceSettingsInfo.cloudResolution = data[4];
                } else if (type == AVIOCTRLDEFs.TCL_CMD_GET_CAMERA_STATUS_RESP) {
                    if (mDeviceSettingsInfo != null) {
                        mDeviceSettingsInfo.deviceStatus = Packet.byteArrayToInt_Little(data, 0);
                        mDevice.is_open = mDeviceSettingsInfo.deviceStatus;
                    }
                    TGLog.d(TAG, "mDevice.is_open = mDeviceSettingsInfo.deviceStatus" + mDevice.is_open);
                } else if (type == AVIOCTRLDEFs.TCI_CMD_SET_COMMAND_RESP) {
                    int command = Packet.byteArrayToInt_Little(data, 0);
                    int result = Packet.byteArrayToInt_Little(data, 4);
                    TGLog.d(TAG, "TCI_CMD_SET_COMMAND_RESP command:"+command+" result =" + result);
                    if (command == AVIOCTRLDEFs.TCL_CMD_SET_CAMERA_STATUS_REQ) {
                        TGLog.d(TAG, "mDeviceSettingsInfo.deviceStatus=========result =" + result);
                        if (result == 0) {
                            Intent intent = new Intent();
                            intent.setAction(SocketIoConstants.NOTIFY_DEVICE_STATUS);
                            JSONObject object = new JSONObject();
                            object.put("device_id", mDevice.id);
                            TGLog.d(TAG, "mDeviceSettingsInfo.deviceStatus=========" + mDevice.is_open);

                            String type1 = SocketIoConstants.DEVICE_STATUS_OPEN;
                            if (mDeviceSettingsInfo != null) {
                                mDeviceSettingsInfo.deviceStatus = mDevice.is_open;
                            }
                            if (mDevice.is_open == DeviceStateConstants.DEVICE_OFF) {
                                type1 = SocketIoConstants.DEVICE_STATUS_SHUTDOWN;
                            }
                            object.put("type", type1);
                            intent.putExtra(SocketIoConstants.NOTIFY_KEY_DATA, object.toJSONString());
                            sendBroadcast(intent);
                        }
                    } else if (command == AVIOCTRLDEFs.TCI_CMD_SET_MICROPHONE_REQ||command ==AVIOCTRLDEFs.TCI_CMD_SET_MICROPHONE_RESP) {
                        if (result == 0) {

                            TGLog.d("CameraViewActivity",  "info.b11 = " + mDeviceSettingsInfo.microphoneOn);
                        }
                    }
                } else if (type == AVIOCTRLDEFs.TCI_CMD_GET_BATTERY_STATUS_RESP) {
                    mDeviceSettingsInfo.batteryPower = Packet.byteArrayToInt_Little(data, 4);
                } else if (type == AVIOCTRLDEFs.TCI_CMD_GET_VOLUME_RESP) {
                    mDeviceSettingsInfo.speakerVolume = Packet.byteArrayToInt_Little(data, 4);
                    mDeviceSettingsInfo.speakerVolume = SpeakerVolumeActivity.adjustProgress(mDeviceSettingsInfo.speakerVolume);
                } else if (type == AVIOCTRLDEFs.TCI_CMD_GET_PIR_RESP) {
                    mDeviceSettingsInfo.pir = Packet.byteArrayToInt_Little(data, 4);
                } else if (type == AVIOCTRLDEFs.TCI_CMD_GET_LED_STATUS_RESP) {
                    mDeviceSettingsInfo.ledStatusOn = Packet.byteArrayToInt_Little(data, 0);
                } else if (type == AVIOCTRLDEFs.TCI_CMD_GET_ALARMLIGHT_RESP) {
                    mDeviceSettingsInfo.alarmLightOn = Packet.byteArrayToInt_Little(data, 4);
                } else if (type == AVIOCTRLDEFs.TCI_CMD_GET_AI_RESP) {
                    mDeviceSettingsInfo.aiOn = Packet.byteArrayToInt_Little(data, 4);
                } else if (type == AVIOCTRLDEFs.TCI_CMD_GET_MICROPHONE_RESP) {
                    byte b = Packet.byteArrayToByte_Little(data, 4);
                    mDeviceSettingsInfo.microphoneOn = b;
                    TGLog.d("CameraViewActivity",  "info.b1122 = " + mDeviceSettingsInfo.microphoneOn);
                } else if (type == AVIOCTRLDEFs.TCI_CMD_SET_MICROPHONE_RESP) {
                    int result = Packet.byteArrayToInt_Little(data, 0);
                    if (result == 0) {
                        TGLog.d("CameraViewActivity",  "info.b331122 = " + mDeviceSettingsInfo.microphoneOn);
                    }
                }
                updateSettings();
                setDeviceState();

            });

        }
    };

    private void rebootCompeted() {
        Intent intent = new Intent();
        intent.setClass(DeviceSettingsActivity.this, DeviceListActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
    }

    private void startrreadui() {
        mIsReadSuccess = false;
        handler.postDelayed(timeRunnable, 15000);
    }

    private void completeread() {
        mIsReadSuccess = true;
        hideLoading();
        handler.removeCallbacks(timeRunnable);
    }

    Runnable timeRunnable = () -> {
        hideLoading();
        if (!mIsReadSuccess) {
          //  showToast(R.string.read_set_fail);
        }
    };


    private void updateSettings() {
        DeviceSettingHelper.updateSettings(deviceFeature, mDeviceSettingsInfo);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data != null){
                String name = data.getStringExtra(DeviceInfoActivity.EXT_DEVICE_NAME);
                if (mDevice != null){
                    mDevice.name = name;
                }
                deviceName.setText(name);
            }

            getServiceInfo();
        }
    }


    private void getServiceInfo() {
        if (mDeviceSettingsInfo == null) return;
        ServiceInfoHelper.getServiceInfo(mDevice.uuid, new ServiceInfoHelper.ServiceInfoListener<HashMap<String, DeviceServiceStatusBean>>() {
            @Override
            public void onSuccess(HashMap<String, DeviceServiceStatusBean> resp) {
                TGLog.i(TAG, "[query][onSuccess] resp = " + resp);
                if (resp != null){
                    DeviceServiceStatusBean deviceServiceStatusBean = resp.get(mDevice.uuid);
                    if (deviceServiceStatusBean != null){
                        mDevice.server_data = deviceServiceStatusBean.storage;
                        mDevice.sim_server_data = deviceServiceStatusBean.sim;
                        mDevice.car_server_data = deviceServiceStatusBean.car;
                        mDevice.ai_server_data = deviceServiceStatusBean.ai;
                        mDevice.foreignServiceHook = deviceServiceStatusBean.foreign_service_hook;
                        if (mDevice.server_bought == null){
                            mDevice.server_bought = new ServiceBought();
                        }
                        mDevice.server_bought.ai_server = deviceServiceStatusBean.bought.ai? 1 : 0;
                        mDevice.server_bought.car_server = deviceServiceStatusBean.bought.car? 1 : 0;
                        mDevice.server_bought.sim_server = deviceServiceStatusBean.bought.sim? 1 : 0;
                        mDevice.server_bought.server = deviceServiceStatusBean.bought.storage? 1 : 0;
                        setDeviceState();
                    }
                }
            }

            @Override
            public void onError(int errorCode, String errorInfo) {
                String msg = "errorCode = " + errorCode + " , errorInfo = " + errorInfo;
                TGLog.i(TAG, "[query][onResponseError] " + msg);
            }
        });
    }




    private final Consumer<ConnectStatus> connectStatusConsumer = new Consumer<ConnectStatus>() {
        @Override
        public void accept(ConnectStatus connectStatus) {
            Status status = connectStatus.getStatus();
            if (status == Status.SUCCESS) {
                getServiceInfo();
            }

            if (NetworkUtil.isNetworkConnected(TGApplicationBase.getApplication())) {

                if (status == Status.SUCCESS) {
                    //long lastLoginTime = PreferenceUtil.getLong(getBaseContext(), CommonConstants.PRE_USER_LOGIN_UPDATED_AT);
                    if (deviceFacade == null) return;
                    // 登陆时间大于最后更新时间，说明重新登陆了，重新登陆了 ，需要更新
                    DeviceInteraction.create(deviceFacade).getFeatureList();
                    sendCmd();
                } else if (status == Status.FAILED || status == status.DISCONNECTED_BY_DEVICE) {
                    if (mDeviceSettingsInfo != null) {
                        mDeviceSettingsInfo.deviceStatus = mDevice.is_open;
                    }

                    TGLog.d(TAG, "===mDeviceSettingsInfo.deviceStatus = ");

                    handler.removeCallbacks(timeRunnable);
                    handler.post(timeRunnable);
                }
            }
        }
    };

}
